<script setup>
import { reactive, ref, watch, onMounted, onBeforeUnmount } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { loadBMapGLScript, getMaskOverlay } from '@T2/utils/BMapGL_API.ts';
import { getUnitsParams } from '@T2/utils/params.ts';
import { mapStyle } from './mapStyle.js';
import { isJSON } from '@T2/utils/utils.ts';
import NormalPNG from '@T2/assets/maps/buoy-normal.png';

const props = defineProps({
  backOri: {
    type: Number,
    default: 0,
  }
});
const emits = defineEmits(['zt-change']);

const clickHandlers = [];
let maps = {};
const Resd = reactive({
  units: undefined,
  sensors: [],
});
  
onMounted(async () => {
  if (!window.BMapGL) {
    await loadBMapGLScript();
  }
  const { unitList, curIds } = await getUnitsParams('/P/Display/home06');
  Resd.units = unitList.filter(i => +i.x && +i.y);
  
  Resd.units.forEach(unit => {
    if (!isJSON(unit.params)) {
      return;
    }
    const paramsObj = JSON.parse(unit.params);
    const { others } = paramsObj || {};
    if (!others?.length) {
      return;
    }
    unit._others = others;
  });
  // const flag = true;
  const flag = import.meta.env.MODE !== 'development';
  flag && mapsInit();
});
const mapsInit = () => {
  if (!Resd.units.length) {
    ElMessage.error('未查询到设置了经纬度的站点！');
    return;
  }
  maps = new window.BMapGL.Map('map_container', { minZoom: 7 });
  maps.setMapStyleV2({styleJson: mapStyle});
  maps.setTilt(0);    // 设置地图倾斜角
  maps.setHeading(0); // 设置地图倾斜角
  maps.enableKeyboard();
  maps.enableScrollWheelZoom();
  maps.enableInertialDragging();
  maps.enableContinuousZoom();
  maps.setDisplayOptions({ poi: true, poiIcon: false});
  
  /* viewPort: { center: {lat: 31.13, lng: 121.1}, zoom: 12 } */
  const points = Resd.units.map(i => new window.BMapGL.Point(+i.x, +i.y));
  const viewPort = maps.getViewport(points);
  // maps.centerAndZoom(viewPort.center, viewPort.zoom > 12 ? 12 : viewPort.zoom);
  maps.centerAndZoom(viewPort.center, viewPort.zoom);
  
  initHome(maps.getCenter(), maps.getZoom());
  
  const icon = new window.BMapGL.Icon(NormalPNG, new window.BMapGL.Size(0, 0));
  Resd.units.forEach(item => {
    const clickHandler = function(e) {
      openInfoWindow(item);
    };
    let marker = new window.BMapGL.Marker(new window.BMapGL.Point(+item.x, +item.y), { icon: icon });
    maps.addOverlay(drawMarker(marker, item));
    marker.addEventListener('click', clickHandler);
    clickHandlers.push({ marker, clickHandler });
  });
}
onBeforeUnmount(() => {
  clickHandlers.forEach(({ marker, clickHandler }) => {
    marker.removeEventListener('click', clickHandler);
  });
});
const drawMarker = (marker, item) => {
  setTimeout(() => {
    let eleName = document.createElement('div');
    eleName.className = 'buoy-name';
    eleName.innerHTML = `<div>${ item.name }</div>`;
    marker.domElement.appendChild(eleName);
    
    let eleIcon = document.createElement('div');
    eleIcon.className = item.warn_number > 0 ? 'map-buoy alarm' : 'map-buoy';
    marker.domElement.appendChild(eleIcon);
  }, 100);
  return marker;
}

/* 点击marker弹窗 */
const detail = reactive({
  data: null,
  dom: null,
});
const openInfoWindow = (item) => {
  const point = new window.BMapGL.Point(+item.x, +item.y);
  const content = `<div class="openTips" id="tipsUnitID${ item.id }"></div>`;
  const infoWindow = new window.BMapGL.InfoWindow(content, {
    width: 0,
    offset: new window.BMapGL.Size(-29, 0), //默认的一个引导箭头,宽58px,高31px,往左偏移一半宽度
  });
  maps.openInfoWindow(infoWindow, point);
  setTimeout(() => {
    detail.dom = document.getElementById(`tipsUnitID${ item.id }`);
  }, 50);
  detail.data = item;
}
const closeInfoWindow = () => {
  maps.closeInfoWindow();
}

/* 回到初始地图位置 */
const homeRt = reactive({
  center: {},
  zoom: 12,
});
watch(() => props.backOri, (nv, ov) => {
  maps.centerAndZoom(homeRt.center, homeRt.zoom);
});
const initHome = (center, zoom) => {
  homeRt.center = center;
  homeRt.zoom = zoom;
}


const goToZt = (unit) => {
  if (!unit._others?.length || !unit._others[0].c?.length) {
    ElMessage.error('未绑定组态页面！');
    return;
  }
  const { t, v } = unit._others[0].c[0];
  if (t !== 'zt' || !v) {
    ElMessage.error('未绑定组态页面！');
    return;
  }
  emits('zt-change', v);
}
</script>

<template>
  <div id="map_container" class="BMap_container"></div>
  
  <teleport :to="detail.dom" v-if="detail.dom && detail.data">
    <div class="popup flex-column">
      <label>{{ detail.data.name }}</label>
      <div class="zt-btn flex--center" @click="goToZt(detail.data)" v-if="detail.data._others?.length">
        <img :src="require('../assets/popup-bg-eye.png')" />
        <span>工艺监控</span>
      </div>
      <template v-if="detail.data._sensors?.length >= 1 && detail.data._sensors[1].c?.length">
        <div class="data-box flex flex-wrap">
          <div class="data-item flex--center" v-for="item in detail.data._sensors[1].c">
            <label>{{ item.n }}：</label>
            <strong>{{ item.value }}</strong>
            <span>&nbsp;({{ item.unit }})</span>
          </div>
        </div>
      </template>
    </div>
  </teleport>
</template>

<style lang="scss" scoped>
@use '@T2/styles/BMap.scss';
.BMap_container {
  width: 100%;
  height: 100%;
  background-color: rgba(0,0,0,0.5);
}
.popup {
  width: 100%;
  height: 100%;
  overflow: hidden;
  padding: 40px 30px 15px;
  >label {
    color: #fff;
  }
}
.data-box {
  margin: 10px 10px 0;
  flex: 1;
  overflow: hidden;
  .data-item {
    min-width: 50%;
    label {
      font-weight: 400;
      font-size: 14px;
      color: #29b2c8;
    }
    strong {
      font-size: 16px;
      font-weight: 600;
      color: #fff;
    }
    span {
      font-size: 12px;
      color: #29b2c8;
    }
  }
}
.zt-btn {
  position: absolute;
  right: 17px;
  top: 28px;
  width: 100px;
  height: 30px;
  line-height: 30px;
  padding: 0 8px;
  font-size: 14px;
  color: #00FF55;
  cursor: pointer;
  white-space: nowrap;
  background: url('../assets/popup-bg-eyebg.png') no-repeat center;
  background-size: 100% 100%;
  &:hover {
    opacity: 0.85;
  }
  img {
    width: 18px;
    height: 18px;
    margin-right: 9px;
  }
}
</style>
<style scoped>
:deep(.BMap_bubble_pop) {
  /* BMap_bubble_top高度为31px,img高度31px，36px为图标高度 */
  transform: translateY(calc(31px + 31px - 71px - 25px));/* px-to-viewport-ignore */
}
:deep(.map-buoy) {
  position: absolute;
  transform: translateX(-50%) translateY(-71px);  /* px-to-viewport-ignore */
  width: 49px;  /* px-to-viewport-ignore */
  height: 71px; /* px-to-viewport-ignore */
  background: url('../assets/map_buoy_ok.png') no-repeat center;
  background-size: 100% 100%;
}
:deep(.map-buoy.alarm) {
  background: url('../assets/map_buoy_ng.png') no-repeat center;
  background-size: 100% 100%;
}
:deep(.openTips) {
  pointer-events: auto !important;
  overflow: hidden;
  z-index: 1000;
  width: 413px;   /* px-to-viewport-ignore */
  height: 196px;  /* px-to-viewport-ignore */
  background: url('../assets/popup-bg.png') no-repeat center;
  background-size: 100% 100%;
}
:deep(.buoy-name) {
  height: 25px;       /* px-to-viewport-ignore */
  line-height: 25px;  /* px-to-viewport-ignore */
  padding: 0 15px;
  position: absolute;
  top: -95px;         /* px-to-viewport-ignore */
  left: 0;
  transform: translateX(-50%);
  font-size: 14px;    /* px-to-viewport-ignore */
  letter-spacing: 2px;
  white-space: nowrap;
  width: fit-content;
  color: #fff;
  background: #02BBC6;
  box-shadow: 0px 2px 4px 0px #609CA0;
  border-radius: 4px;
}

:deep(.tool-btn .el-icon:hover) {
  color: #00FFFF;
}
</style>